<?php

namespace app\api\controller\shop;


use app\admin\model\Onlineshopprofit;
use app\admin\model\Shop;
use app\admin\model\Shopcharge;
use app\admin\model\Shopmtdyprofit;
use app\admin\model\Shopmtdywith;
use app\admin\model\Shoporder;
use app\admin\model\Shopstaff;
use app\admin\model\Useragent;
use app\admin\model\Usercard;
use app\admin\model\Userwithdraw;
use app\api\service\BalanceService;
use app\api\service\BankService;
use app\api\service\CommonService;
use app\common\controller\Api;

/**
 *
 */
class Money extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];



    public function data()
    {
        $user = $this->auth->getUser();
        $balanceService = new BalanceService();
        $balance = $balanceService->shopBalance($user['id']);

        $shop_id = $this->request->param('shop_id');

        $shopModel = new Shop();
        $shopList = $shopModel->where('user_id',$user['id'])->select();
        $ids = array();
        foreach ($shopList as $key=>$val){
            $ids[] = $val['id'];
        }

        $shopOrderModel = new Shoporder();
        $totalAmount = $shopOrderModel->where('shop_id','in',$ids)->where('status','in',['payed','doing','done'])->sum('amount');
        if($totalAmount >10000){
            $totalAmount = round($totalAmount/10000,2)."万";
        }

        $payRate = $shopOrderModel->where('shop_id','in',$ids)->where('status','in',['payed','doing','done'])->sum('pay_rate');


        $payAmount = $shopOrderModel->where('shop_id','in',$ids)->where('status','in',['payed','doing','done'])->sum('pay_amount');
        if($payAmount >10000){
            $payAmount = round($payAmount/10000,2)."万";
        }

        $userWithDrawModel = new Userwithdraw();
        $withAmount = $userWithDrawModel->where('user_id',$user['id'])->where('type','shop')->sum('amount');


        $shopMtdyProfitModel =new Shopmtdyprofit();
        $mtAmount = $shopMtdyProfitModel->where('type','meituan')->where('shop_id','in',$ids)->sum('amount');
        $dyAmount = $shopMtdyProfitModel->where('type','douyin')->where('shop_id','in',$ids)->sum('amount');

        $chargeOrderModel = new Shopcharge();
        $chargeAmount = $chargeOrderModel->where('shop_id',$shop_id)->where('status','payed')->sum('amount');
        if($chargeAmount >10000){
            $chargeAmount = round($chargeAmount/10000,2)."万";
        }

        $mtFee = $shopMtdyProfitModel->where('type','meituan')->where('shop_id','in',$ids)->sum('fee');
        $dyFee = $shopMtdyProfitModel->where('type','douyin')->where('shop_id','in',$ids)->sum('fee');


        $onlineShopProfitModel = new Onlineshopprofit();
        $onlineAmount = $onlineShopProfitModel->where('shop_id','in',$ids)->sum('amount');

        $shopMtdyWithModel = new Shopmtdywith();
        $mtdyDisAmount = $shopMtdyWithModel->where('user_id',$user['id'])->sum('amount');
        $ret = array();
        $ret['totalAmount'] = $totalAmount;
        $ret['balance'] = $balance;
        $ret['payAmount'] = $payAmount;
        $ret['withAmount'] = $withAmount;
        $ret['mtAmount'] = $mtAmount;
        $ret['dyAmount'] = $dyAmount;
        $ret['chargeAmount'] = $chargeAmount;

        $ret['ksAmount'] = 0;
        $ret['payRate'] = $payRate;
        $ret['onlineAmount'] = $onlineAmount;
        $ret['dyRate'] = formatMoney($dyFee);
        $ret['mtRate'] = formatMoney($mtFee);
        $ret['mtDyUnDis'] = round($ret['dyRate']+$ret['mtRate']-$mtdyDisAmount,2);
        $ret['keBalance'] = round($balance- $ret['mtDyUnDis'],2);


        $this->success(json_encode($ids),$ret);
    }


    public function data2()
    {
        $user = $this->auth->getUser();
        $balanceService = new BalanceService();
        $shop_id = $this->request->param('shop_id');
        $balance = $balanceService->shopBalance($user['id']);


        $shopModel = new Shop();
        $shopList = $shopModel->where('user_id',$user['id'])->select();
//        $ids = array();
//        foreach ($shopList as $key=>$val){
//            $ids[] = $val['id'];
//        }

        $chargeOrderModel = new Shopcharge();
        $chargeAmount = $chargeOrderModel->where('shop_id',$shop_id)->where('status','payed')->sum('amount');
        if($chargeAmount >10000){
            $chargeAmount = round($chargeAmount/10000,2)."万";
        }


        $shopOrderModel = new Shoporder();
        $totalAmount = $shopOrderModel->where('shop_id',$shop_id)->where('status','in',['payed','doing','done'])->sum('amount');
        if($totalAmount >10000){
            $totalAmount = round($totalAmount/10000,2)."万";
        }

        $payRate = $shopOrderModel->where('shop_id',$shop_id)->where('status','in',['payed','doing','done'])->sum('pay_rate');




        $payAmount = $shopOrderModel->where('shop_id',$shop_id)->where('status','in',['payed','doing','done'])->sum('pay_amount');
        if($payAmount >10000){
            $payAmount = round($payAmount/10000,2)."万";
        }

        $userWithDrawModel = new Userwithdraw();
        $withAmount = $userWithDrawModel->where('user_id',$user['id'])->where('type','shop')->sum('amount');


        $shopMtdyProfitModel =new Shopmtdyprofit();
        $mtAmount = $shopMtdyProfitModel->where('type','meituan')->where('shop_id',$shop_id)->sum('amount');
        $dyAmount = $shopMtdyProfitModel->where('type','douyin')->where('shop_id',$shop_id)->sum('amount');

        $shopMtdyWithModel = new Shopmtdywith();
        $mtdyDisAmount = $shopMtdyWithModel->where('user_id',$user['id'])->sum('amount');
        $ret = array();
        $ret['totalAmount'] = $totalAmount;
        $ret['balance'] = $balance;
        $ret['payAmount'] = $payAmount;
        $ret['withAmount'] = $withAmount;
        $ret['mtAmount'] = $mtAmount;
        $ret['dyAmount'] = $dyAmount;
        $ret['ksAmount'] = 0;
        $ret['chargeAmount'] = $chargeAmount;



        $ret['payRate'] = $payRate;
        $ret['dyRate'] = round($dyAmount*0.06,2);
        $ret['mtRate'] = round($mtAmount*0.06,2);
        $ret['mtDyUnDis'] = round($ret['dyRate']+$ret['mtRate']-$mtdyDisAmount,2);
        $ret['keBalance'] = round($balance- $ret['mtDyUnDis'],2);


        $this->success("",$ret);
    }


    public function configInit(BalanceService $balanceService){
        $ret = array();
        $role = $this->request->param('role');
        $shopId = $this->request->param('shopId');
        //1. 是否实名
        $user = $this->auth->getUser();
        $userModel = new \app\admin\model\User();
        $user = $userModel->where('id',$user['id'])->find();
        if($user['idcard'] == ''){
            $this->error("","",-2);
        }
        $ret['username'] = $user['username'];

        //2. 是否添加银行卡
        $userCardModel = new Usercard();
        $userCard =  $userCardModel->where('user_id',$user['id'])->find();
        if($userCard == null){
            $this->error("",$ret,-3);
        }
        $shopModel = new \app\admin\model\Shop();
        if($shopId){
            $shop = $shopModel->where('id',$shopId)->find();
            if($shop['is_profile'] == -1){
                $this->error("",'',-4);

            }
        }


        $ret['card'] = $userCard;
        if($role =='商家'){
            $balance = $balanceService->shopBalance($user['id']);

        }else if($role == '代理商'){
            $balance = $balanceService->agentBalance($user['id']);
        }else if($role == '助教'){
            $balance = $balanceService->assBalance($user['id']);
        }else{
            $balance = 0;
        }

        if($role =='商家'){
            $shopModel = new Shop();
            $shopList = $shopModel->where('user_id',$user['id'])->select();
            $ids = array();
            foreach ($shopList as $key=>$val){
                $ids[] = $val['id'];
            }
            $shopMtdyProfitModel =new Shopmtdyprofit();
            $mtAmount = $shopMtdyProfitModel->where('type','meituan')->where('shop_id','in',$ids)->sum('fee');
            $dyAmount = $shopMtdyProfitModel->where('type','douyin')->where('shop_id','in',$ids)->sum('fee');

            $shopMtdyWithModel = new Shopmtdywith();
            $mtdyDisAmount = $shopMtdyWithModel->where('user_id',$user['id'])->sum('amount');


            $ret['dyRate'] = $dyAmount;
            $ret['mtRate'] = $mtAmount;
            $ret['mtDyUnDis'] = round($ret['dyRate']+$ret['mtRate']-$mtdyDisAmount,2);

            $ret['balance'] = round($balance- $ret['mtDyUnDis'],2);;
        }else{
            $ret['balance'] = $balance;
        }


        $this->success('',$ret);
    }

    /**
     * 实名
     */
    public function verify(CommonService $commonService){

        $username = $this->request->param('name');
        $idcard = $this->request->param('idcard');

        $userModel = new \app\admin\model\User();
//        $user = $userModel->where('idcard',$idcard)->find();
//        if($user){
//            $this->error("此身份证已实名过");
//        }
        $ret = $commonService->verify($idcard, $username);
        $obj = json_decode($ret, true);
        $status = $obj['status'];
        $msg = $obj['msg'];
        $user = $this->auth->getUser();
        if ($status == '01') {//通过
            $userModel->where('id', $user['id'])->update(['username' => $username,'idcard'=>$idcard]);
            $this->success('');
        } else {
          $this->error($msg);
        }

    }

    public function addBank(){

        $bankNum = $this->request->param('bankCard');
        $bankPhone = $this->request->param('bankPhone');


        $bankNum = str_replace(' ', '', $bankNum);
        $bankService = new BankService();
        $ret = $bankService->checkBank($bankNum);
        $data = json_decode($ret, true);
        $stat = $data['stat'];
        $bankName = "";
        $bankCode = "";

        if ($stat == 'ok') {
            $validated = $data['validated'];
            if (!$validated) {
                $this->error("卡号校验错误,请检查一遍");
            }
            $bankCode = $data['bank'];
            $bankName = json_decode($bankService->banks, true)[$bankCode];
        } else {
            $this->error("卡号错误,请检查一遍");

        }

        $uid = $this->auth->getUser()['id'];
        $user = $this->auth->getUser();
        $insertData = array();
        $insertData['user_id'] = $uid;
        $insertData['bank_name'] = $bankName;
        $insertData['bank_code'] = $bankCode;
        $insertData['bank_icon'] = "https://yangfubing.gitee.io/bank.logo/resource/logo/" . $bankCode . ".png";
        $insertData['card_num'] = $bankNum;
        $insertData['bank_phone'] = $bankPhone;
        $insertData['user_name'] = $user['username'];

        $userCardModel = new Usercard();
        $bank = $userCardModel->where('user_id',$uid)->find();
        if($bank){
            $userCardModel->where('id', $bank['id'])->update($insertData);
        }else{
            $userCardModel->insert($insertData);
        }
        $this->success('成功');
    }


    /**
     * 提现
     */
    public function doShopWithDraw(BalanceService $balanceService){
        $db = array();
        $amount = $this->request->param('amount');
        $role = $this->request->param('role');
        $user = $this->auth->getUser();
        $userWithDrawModel = new Userwithdraw();

        $fee = 0;
        if($role == '商家'){
            $balance = $balanceService->shopBalance($user['id']);
            $db['type'] = 'shop';

            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('user_id',$user['id'])->find();
            $todayCount = $userWithDrawModel->where('user_id',$user['id'])->whereTime("create_time",'today')->count('id');
            if($shop['org_id'] == 27){

                if($todayCount >=1 ){
                    $this->error("当天只能提现一次");
                }
                if($amount<100){
                    $this->error("单笔必须要大于100");
                }

                if($amount>10000){
                    $this->error("单笔不能超过1W");
                }

            }
        }else if($role == '代理商'){
            $db['type'] = 'user';
            $balance = $balanceService->agentBalance($user['id']);
        }else if($role == '助教'){
            $balance= $balanceService->assEnableBalance($user['id']);
            $db['type'] = 'assistant';

        }else{
            $balance = 0;

        }

        $startToday = strtotime(date("Y-m-d") . " 09:30:00");
        $endToday = strtotime(date("Y-m-d") . " 16:00:00");
        if (time() < $startToday || time() > $endToday) {
            $this->error("不在提现时间段09:30 ~ 16:00");
        }


        if($balance< $amount){
            $this->error("余额不足");
        }



        $url = "http://vip.bitefu.net/jiari/?d=".date('Ymd')."&apikey=1eae257e44aa9d5b";
//
        $res = file_get_contents($url);    //json格式，前端需要直接提供
//
        $res = json_decode($res,true);
        $key = $res['data'];
        if($key != 0){
            $this->error("节假日或者周末不可提现");
        }
        if($role == '商家'){
            $shopModel = new Shop();
            $shopList = $shopModel->where('user_id',$user['id'])->select();
            $ids = array();
            foreach ($shopList as $key=>$val){
                $ids[] = $val['id'];
            }
            $shopMtdyProfitModel =new Shopmtdyprofit();
            $mtAmount = $shopMtdyProfitModel->where('type','meituan')->where('shop_id','in',$ids)->sum('fee');
            $dyAmount = $shopMtdyProfitModel->where('type','douyin')->where('shop_id','in',$ids)->sum('fee');

            $shopMtdyWithModel = new Shopmtdywith();
            $mtdyDisAmount = $shopMtdyWithModel->where('user_id',$user['id'])->sum('amount');


            $ret = array();
            $ret['dyRate'] = $dyAmount;
            $ret['mtRate'] = $mtAmount;
            $ret['mtDyUnDis'] = round($ret['dyRate']+$ret['mtRate']-$mtdyDisAmount,2);

            $balance = round($balance- $ret['mtDyUnDis'],2);;
            if($balance< $amount){
                $this->error("余额不足");
            }
        }








        $userCardModel = new Usercard();
        $card = $userCardModel->where('user_id',$user['id'])->find();
        $db['user_id'] = $user['id'];
        $db['user_name'] = $card['user_name'];
        $db['bank_num'] = $card['card_num'];
        $db['amount'] = $amount;
        $db['back_amount'] = $amount-$fee;
        $db['create_time'] = time();
        $db['status'] = 'doing';

        $id = $userWithDrawModel->insertGetId($db);

        if($role == '商家'){
            if( $ret['mtDyUnDis'] > 0){
                $shopMtdyWithModel = new Shopmtdyprofit();
                $shopMtdyWithModel->insert(['amount'=>$ret['mtDyUnDis'],'with_id'=>$id,'create_time'=>time(),'user_id'=>$user['id']]);
            }
        }



            $this->success('成功');

    }


    public function withDrawList(){

        $user = $this->auth->getUser();
        $page = $this->request->param("page");
        $type = $this->request->param('type');
        $limit = 10;
        $offset = ($page - 1) * $limit;
        $userWithDrawModel = new Userwithdraw();
        $total = $userWithDrawModel->where('type',$type)->where('user_id',$user['id'])->sum('amount');

        $list = $userWithDrawModel->where('type',$type)->where('user_id',$user['id'])->order('create_time','desc')->limit($offset,$limit)->select();
        foreach ($list as $key=>$val){
            if($val['status'] == 'doing'){
                $list[$key]['status'] = '处理中';
            }else if(($val['status'] == 'success')){
                $list[$key]['status'] = '处理成功';
            }
            $list[$key]['create_time_txt'] = date('Y-m-d',$val['create_time']);
        }
        $ret = array();
        $ret['total'] = $total;
        $ret['list'] = $list;





        $this->success('',$ret);

    }

}
